<?php

abstract class flickr {
	private $api_key = 'ecd86da41beb356cbb702bcf4485af17';
	private $endpoint = 'http://api.flickr.com/services/rest/';
	
	// queries flickr and returns formatted result
	protected function get_json($method, $args) {
		$args = http_build_query($args);
		$json_url = "{$this->endpoint}?api_key={$this->api_key}&format=json&nojsoncallback=1&method=$method&$args";
		return json_decode(file_get_contents($json_url));
	}
	
	abstract function render(); 
}

class photoset extends flickr {
	private $photoset_id;
	
	public function __construct($photoset_url) {
		// parses through url to get photoset_id (last part of url)
		// the photoset_id will be used in every method of this class
		$path = parse_url($photoset_url, PHP_URL_PATH);
		$path_parts = array_filter(explode('/', $path));
		$this->photoset_id = end($path_parts);
	}
		
	// display the photoset meta info, for an article view
	public function render_info() {
		$args = array(
			'photoset_id' => $this->photoset_id,
		);
		$photoset_data = $this->get_json('flickr.photosets.getInfo', $args);
		
		echo "<p>{$photoset_data->photoset->description->_content}</p>";		
	}
	
	// preview: only display a few photos from this set, for use on a category view
	public function render_preview() {
		// gets square photo for thumbnail, and the large and original size photos for fullsize view
		// gets original incase the large photo size doesn't exist (in that case, original is smaller than large)
		$args = array(
			'photoset_id' => $this->photoset_id,
			'extras' => 'url_sq, url_l, url_o',
			'per_page' => '14'
		);
		$photoset_data = $this->get_json('flickr.photosets.getPhotos', $args);
		foreach ($photoset_data->photoset->photo as $photo_data) {
			if ($photo_data->url_l)
				$full_photo_url = $photo_data->url_l;
			else
				$full_photo_url = $photo_data->url_o;
			echo "<a href=\"$full_photo_url\"><img alt=\"{$photo_data->title}\" src=\"{$photo_data->url_sq}\"></a> ";
		}
	}
	
	// display the full set of photos, for an article view
	public function render() {
		// gets small photo for thumbnail, and the large and original size photos for fullsize view
		// gets original incase the large photo size doesn't exist (in that case, original is smaller than large)
		$args = array(
			'photoset_id' => $this->photoset_id,
			'extras' => 'url_s, url_l, url_o',
		);
		$photoset_data = $this->get_json('flickr.photosets.getPhotos', $args);
		foreach ($photoset_data->photoset->photo as $photo_data) {
			if ($photo_data->url_l)
				$full_photo_url = $photo_data->url_l;
			else
				$full_photo_url = $photo_data->url_o;
			echo "<div class=\"photobox\">";
			echo "<a href=\"$full_photo_url\"><img alt=\"{$photo_data->title}\" src=\"{$photo_data->url_s}\"></a>";
			echo "</div>";
		}
	}
}

?>